package com.chainyoung.component_tmperson.ui.activity.financing;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chainyoung.common.base.BaseActivity;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.event.BaseEvent;
import com.chainyoung.common.utils.SPUtil;
import com.chainyoung.common.utils.StringUtil;
import com.chainyoung.common.utils.ToastUtil;
import com.chainyoung.common.view.kprogresshud.KProgressHUD;
import com.chainyoung.component_tmperson.R;
import com.chainyoung.component_tmperson.R2;
import com.chainyoung.component_tmperson.di.component.DaggerPersonActivityComponent;
import com.chainyoung.component_tmperson.di.module.PersonActivityModule;
import com.chainyoung.component_tmperson.entity.WalletFinancing;
import com.chainyoung.component_tmperson.entity.WalletFinancingOwn;
import com.chainyoung.component_tmperson.ui.mvp.contract.WalletFinancingTradeContract;
import com.chainyoung.component_tmperson.ui.mvp.presenter.WalletFinancingTradePresenter;

import org.simple.eventbus.EventBus;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;

import static com.chainyoung.common.event.BaseEvent.EventCode.REFRESH_FINANCING_TRADE;

/**
 * 购买增益
 */
public class WalletFinancingTradeActivity extends BaseActivity<WalletFinancingTradePresenter> implements WalletFinancingTradeContract.View {


    @BindView(R2.id.tv_coin_type)
    TextView tvCoinType;
    @BindView(R2.id.tv_own_coin_num)
    TextView tvOwnCoinNum;
    @BindView(R2.id.tv_pro_type)
    TextView tvProType;
    @BindView(R2.id.rl_select_type)
    RelativeLayout rlSelectType;
    @BindView(R2.id.txt_buy_num)
    TextView txtBuyNum;
    @BindView(R2.id.et_num)
    EditText etNum;
    @BindView(R2.id.tv_fee)
    TextView tvFee;
    @BindView(R2.id.tv_buy_all)
    TextView tvBuyAll;
    @BindView(R2.id.tv_send)
    TextView tvSend;
    @BindView(R2.id.et_remark)
    EditText etRemark;

    private WalletFinancing data;
    private WalletFinancingOwn own;
    private static final int REQUEST_PRO_TYPE = 0x1111;
    private WalletFinancing.ListBean selectPro;
    private String type = "";


    private final static String TYPE_ACTIVE = "current";//活期
    private final static String TYPE_FIXED = "fixed";//定期

    private boolean isFirstTrade;

    private List<WalletFinancing.ListBean> mActiveList = new ArrayList<>();
    private List<WalletFinancing.ListBean> mFixedList = new ArrayList<>();


    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerPersonActivityComponent.builder()
                .appComponent(appComponent)
                .personActivityModule(new PersonActivityModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initUI() {
        data = (WalletFinancing) getIntent().getSerializableExtra("walletFinancing");
        type = getIntent().getStringExtra("type");
        isFirstTrade = getIntent().getBooleanExtra("isFirstTrade", false);
        setCurrentTitle(data.getName().toUpperCase() + "转入增益账户");
        tvCoinType.setText("0 " + data.getName().toUpperCase());
        tvFee.setText("划转费：0");
        setListener();
        initSelectType();
    }

    private void setListener() {
        etNum.addTextChangedListener(new TextWatcher() {
            boolean deleteLastChar;// 是否需要删除末尾

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (s.toString().contains(".")) {
                    // 如果点后面有超过6位数值,则删掉最后一位
                    int length = s.length() - s.toString().lastIndexOf(".");
                    // 说明后面有8位数值
                    deleteLastChar = length >= 10;
                }

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
                    return;
                }

                if (deleteLastChar) {
                    // 设置新的截取的字符串
                    etNum.setText(s.toString().substring(0, s.toString().length() - 1));
                    // 光标强制到末尾
                    etNum.setSelection(etNum.getText().length());
                    KProgressHUD.create(mContext)
                            .setCustomView(mContext, R.drawable.tips_error)
                            .setLabel(getString(R.string.tmtrade_only_eight))
                            .show().setDuration(1500);
                }

                // 以小数点开头，前面自动加上 "0"
                if (s.toString().startsWith(".")) {
                    etNum.setText("0" + s);
                    etNum.setSelection(etNum.getText().length());
                }
                if (s.toString().startsWith("0") && (s.toString().length() > 1) && !s.toString().startsWith("0.")) {
                    etNum.setText(s.toString().substring(1));
                    etNum.setSelection(etNum.getText().length());
                }

//                if (own.getCloud_coin_num().compareTo(BigDecimal.ZERO) <= 0) {
//                    etNum.setText("0");
//                    etNum.setSelection(etNum.getText().toString().length());
//                    return;
//                }

                if (new BigDecimal(etNum.getText().toString().trim()).compareTo(own.getCloud_coin_num()) > 0) {
                    etNum.setText(own.getCloud_coin_num().stripTrailingZeros().toPlainString());
                    etNum.setSelection(etNum.getText().toString().length());
                }
                countFee();
            }
        });
    }

    private void initSelectType() {
        mActiveList.clear();
        mFixedList.clear();
        for (WalletFinancing.ListBean item : data.getList()) {
            if (item.getType().equals("current")) {
                mActiveList.add(item);
            } else if (item.getType().equals("fixed")) {
                mFixedList.add(item);
            }
        }
        switch (type) {
            case TYPE_ACTIVE:
                selectPro = mActiveList.get(0);
                tvProType.setText("活期");
                type = selectPro.getType();


                break;
            case TYPE_FIXED:
                selectPro = mFixedList.get(0);
                tvProType.setText(selectPro.getFixed_time() + "天定期");
                type = selectPro.getType();
                break;
            default:
                selectPro = null;
                tvProType.setText("请选择");
        }
    }


    @Override
    public void onLeftViewClicked(View view) {

        if (isFirstTrade) {
            finish();
        } else {
           /* Intent intent = new Intent(mContext, WalletFinancingProfitActivity.class);
            intent.putExtra("type", type);
            intent.putExtra("walletFinancing", this.data);
            mContext.startActivity(intent);
            overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);*/
            EventBus.getDefault().post(new BaseEvent<>(REFRESH_FINANCING_TRADE,type));
            finish();
        }
    }

    @Override
    public void onBackPressed() {
        if (isFirstTrade) {
            finish();
        } else {
            /*Intent intent = new Intent(mContext, WalletFinancingProfitActivity.class);
            intent.putExtra("type", type);
            intent.putExtra("walletFinancing", this.data);
            mContext.startActivity(intent);
            overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);*/
            EventBus.getDefault().post(new BaseEvent<>(REFRESH_FINANCING_TRADE,type));
            finish();
        }
    }

    /**
     * 计算手续费
     */
    private void countFee() {
        if (StringUtil.viewGetTextIsEmpty(etNum)) {
            tvFee.setText("划转费：0");
        } else {
            BigDecimal bdFee = new BigDecimal(StringUtil.viewGetText(etNum)).multiply(new BigDecimal(data.getCharge_in()).divide(new BigDecimal(100)));
            tvFee.setText("划转费：" + StringUtil.subZeroAndDot(bdFee.toPlainString()) + data.getName().toUpperCase());
        }
    }

    @Override
    protected void initData() {
        getBalance();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.tmperson_activity_financing_trade;
    }


    @OnClick(R2.id.tv_buy_all)
    void buyAll() {
        etNum.setText(StringUtil.subZeroAndDot(own.getCloud_coin_num().setScale(8, RoundingMode.DOWN).toPlainString()));
        etNum.setSelection(etNum.getText().toString().length());
    }

    @OnClick(R2.id.tv_send)
    void send() {
        if (selectPro == null) {
            ToastUtil.showToast("请选择增益类型");
            return;
        }
        if (own.getCloud_coin_num().compareTo(BigDecimal.ZERO) <= 0) {
            ToastUtil.showToast("您的余额不足");
            return;
        }

        if (StringUtil.viewGetTextIsEmpty(etNum)) {
            ToastUtil.showToast("请输入转入数量");
            return;
        }

        if (new BigDecimal(etNum.getText().toString().trim()).compareTo(BigDecimal.ZERO) <= 0) {
            ToastUtil.showToast("转入数量不能小于等于0");
            return;
        }

        AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(mContext);
        builder.setMessage(R.string.tmperson_confirm_buy)
                .setPositiveButton(mContext.getString(R.string.confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // launch(SetPinCodeActivity.class);
                        confirmTurnIn();
                        dialog.dismiss();
                    }
                })
                .setNegativeButton(mContext.getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder.create();
        builder.show();

        /*if (TextUtils.isEmpty(SPUtil.getString(LibConstant.PIN_CODE))) {
            AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(mContext);
            builder.setMessage(R.string.tmperson_setting_pincode)
                    .setPositiveButton(mContext.getString(R.string.confirm), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            launch(SetPinCodeActivity.class);
                            dialog.dismiss();
                        }
                    })
                    .setNegativeButton(mContext.getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            builder.create();
            builder.show();
            return;
        } else {
            new PayPwdDialog(mContext, WalletFinancingTradeActivity.this).show();
        }*/


    }

    @OnClick(R2.id.rl_select_type)
    void selectType() {
        Intent intent = new Intent(mContext, SelectFinaningProTypeActivity.class);
        intent.putExtra("walletFinancing", data);
        mContext.startActivityForResult(intent, REQUEST_PRO_TYPE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_PRO_TYPE:
                selectPro = (WalletFinancing.ListBean) data.getSerializableExtra("result");
                tvProType.setText(selectPro.getType().equals("current") ? "活期" : selectPro.getFixed_time() + "天定期");
                type = selectPro.getType();
                if (selectPro.getType().equals("current")) {
                    tvCoinType.setText(own.getCurrent_sum().stripTrailingZeros().toPlainString() + this.data.getName().toUpperCase());
                } else {
                    tvCoinType.setText(own.getFixed_sum().stripTrailingZeros().toPlainString() + this.data.getName().toUpperCase());
                }
                break;
        }
    }


   /* @Override
    public void onInputOver(String password) {
        if (password.equals(SPUtil.getString(LibConstant.PIN_CODE))) {
            confirmTurnIn();
        } else {
            ToastUtil.showToast("您输入的密码有误");
            return;
        }
    }*/


    private void getBalance() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put(LibConstant.TOKEN, SPUtil.getString(LibConstant.TOKEN));
        map.put("coin", data.getName());
        mPresenter.getUserFinancingProfit(map);
    }

    private void confirmTurnIn() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put(LibConstant.TOKEN, SPUtil.getString(LibConstant.TOKEN));
        map.put("coin", data.getName());
        map.put("pm_id", selectPro.getId());
        map.put("num", StringUtil.viewGetText(etNum));
        if (!StringUtil.viewGetTextIsEmpty(etRemark)) {
            map.put("remark", StringUtil.viewGetText(etRemark));
        }
        mPresenter.turnIn(map);
    }


    @Override
    public void onGetUserFinancingProfitSuccess(WalletFinancingOwn data) {
        own = data;
        tvOwnCoinNum.setText(StringUtil.subZeroAndDot(data.getCloud_coin_num().toPlainString()) + data.getCoin_name().toUpperCase());
        if (TextUtils.isEmpty(type)) {
            return;
        }
        if (type.equals(TYPE_ACTIVE)) {
            tvCoinType.setText(own.getCurrent_sum().stripTrailingZeros().toPlainString() + data.getCoin_name().toUpperCase());

        } else if (type.equals(TYPE_FIXED)) {
            tvCoinType.setText(own.getFixed_sum().stripTrailingZeros().toPlainString() + data.getCoin_name().toUpperCase());
        }

    }

    @Override
    public void onGetUserFinancingProfitFailed() {

    }

    @Override
    public void onTurnInSuccess(String data) {
        ToastUtil.showToast(data);
        EventBus.getDefault().post(new BaseEvent<>(REFRESH_FINANCING_TRADE,type));
        finish();
    }


}
